package vn.gq.app4vn.doctruyen;

import java.util.ArrayList;
import vn.gq.app4vn.doctruyen.Configuration.DataMode;
import vn.gq.cd.adutils.BannerHelper;
import vn.gq.cd.adutils.StartAppHelper;
import vn.gq.cd.adutils.BannerHelper.BannerType;
import vn.gq.cd.adutils.IntersitialHelper;
import vn.gq.cd.adutils.IntersitialHelper.IntersititalAdType;
import vn.gq.cd.model.bean.BookmarkItem;
import vn.gq.cd.model.bean.CategoryItem;
import vn.gq.cd.model.bean.ChapterItem;
import vn.gq.cd.theme.IBackgroundChangeListener;
import vn.gq.cd.view.WebviewReaderFragment;
import vn.gq.cd.widget.NumberPicker;
import vn.gq.cd.widget.PopupWindow;
import vn.gq.cd.widget.ViewPager;
import vn.gq.tym.utils.DialogHelper;
import vn.gq.tym.utils.IDialogHelper;
import vn.gq.tym.utils.IScrollListener;
import vn.gq.tym.utils.NetworkUtils;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ReaderActivity extends BaseActivity implements OnPageChangeListener, OnGestureListener, OnDoubleTapListener, IScrollListener, IBackgroundChangeListener {
	
	private ArrayList<ChapterItem> mChapterItems;
	private ViewPager mViewPager;
	private ReaderPagerAdapter mAdapter;
	private ReaderButtonHandler mButtonHandler;
	private Handler mHandler = new Handler();
	private CategoryItem mCategoryItem;
	private int mCurrentPos = 0;
	private int mScrollPosY = 0;
	private PopupWindow mPopupWindow;
	private LinearLayout mMainLayout;
	private BannerHelper mBannerHelper;
	private boolean firstTime = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(ReaderSettings.getInstance(this).isNightMode() ? R.style.Theme_Sherlock : R.style.Theme_Apptheme);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reader);
		mMainLayout = (LinearLayout) findViewById(R.id.reader_layout_container);
		NetworkUtils.newInstance(ReaderActivity.this).check();
		Bundle bundle = getIntent().getExtras();
//		mChapterItems = bundle.getParcelableArrayList("DATA");
		mChapterItems = (ArrayList<ChapterItem>) ((UngDungVietApp) getApplication()).chapterList;
		mCategoryItem = bundle.getParcelable("CATEGORY");
		mCurrentPos = bundle.getInt("POSITION");
		mScrollPosY = bundle.getInt("SCROLLPOSY");
		firstTime = bundle.getBoolean("FIRSTTIME");
		mButtonHandler = new ReaderButtonHandler((ImageView) findViewById(R.id.btnPrev), (ImageView) findViewById(R.id.btnNext));
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setPagingEnable(false);
		mAdapter = new ReaderPagerAdapter(getSupportFragmentManager());
		mViewPager.setOnPageChangeListener(this);
		mViewPager.setAdapter(mAdapter);
		Toast.makeText(this, "Chạm 2 lần vào màn hình để tùy chỉnh !", Toast.LENGTH_LONG).show();
		initializePopupWindow();
		mViewPager.setCurrentItem(mCurrentPos);
		mButtonHandler.showButton(mCurrentPos);
		setSubtitle(mCurrentPos);
		if (!((UngDungVietApp) getApplication()).admAdLoaded) {
			new AdmobAdLoader(this).load();
		}
		LinearLayout adLayout = (LinearLayout) findViewById(R.id.adLayout);
		BannerType adType = (Configuration.TYPE_AD_ADMOB) ? BannerType.BANNER : BannerType.O_BANNER;
		mBannerHelper = new BannerHelper(this, adLayout, adType);
		IntersititalAdType intersitialAdType = (Configuration.TYPE_AD_ADMOB) ? IntersititalAdType.INTERSITIAL : IntersititalAdType.O_INTERSITIAL;
		IntersitialHelper intersitialHelper = new IntersitialHelper(this, null, intersitialAdType);
//		if (firstTime) {
//			intersitialHelper.loadAd();
//		}
	}
	
	public void savedBookmark() {
		try {
			BookmarkItem item = new BookmarkItem();
			item.catName = mCategoryItem.getName();
			item.catUrl = mCategoryItem.getPath();
			item.chapterName = mChapterItems.get(mCurrentPos).getName();
			item.chapterPos = mCurrentPos;
			item.lasPosition = mCurrentPos;
			item.scrollPosY = mScrollPosY;
			SharedPreferences pref = getSharedPreferences(PREF_BOOKMARK_NAME, MODE_PRIVATE);
			pref.edit().putString("bookmark", item.toJSONObject().toString()).commit();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void initializePopupWindow() {
		final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mPopupWindow = new PopupWindow(this);
		ViewGroup popupView = (ViewGroup) inflater.inflate(R.layout.popup, null, false);
		mPopupWindow.setContentView(popupView);
		((Button) popupView.findViewById(R.id.btnDayMode)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ReaderSettings.getInstance(ReaderActivity.this).setNightMode(false);
				mViewPager.getAdapter().notifyDataSetChanged();
				if (mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
				}
			}
		});
		
		((Button) popupView.findViewById(R.id.btnNightMode)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ReaderSettings.getInstance(ReaderActivity.this).setNightMode(true);
				mViewPager.getAdapter().notifyDataSetChanged();
				if (mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
				}
			}
		});
		
		((Button) popupView.findViewById(R.id.btnChangeFont)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final ReaderSettings setting = ReaderSettings.getInstance(ReaderActivity.this);
				AlertDialog.Builder builder = new Builder(ReaderActivity.this);
				View pickerView = inflater.inflate(R.layout.number_picker_layout, null, false);
				final NumberPicker numberPicker = (NumberPicker) pickerView.findViewById(R.id.numberPicker);
				numberPicker.setMaxValue(36);
				numberPicker.setMinValue(14);
				numberPicker.setValue(setting.getFontSize(20));
				builder
				.setTitle("Chọn kích thước font chữ")
				.setView(pickerView)
				.setInverseBackgroundForced(true)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						int size = numberPicker.getValue();
						setting.setFontSize(size);
						mViewPager.getAdapter().notifyDataSetChanged();
					}
				})
				.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				})
				.create().show();
				
			}
		});
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if (mBannerHelper != null) mBannerHelper.onStop();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mBannerHelper != null) mBannerHelper.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mBannerHelper != null) mBannerHelper.loadAd();
		if (ReaderSettings.getInstance(this).isNightMode()) {
			mMainLayout.setBackgroundResource(R.color.background_holo_dark);
		} else {
			mMainLayout.setBackgroundResource(R.color.background_holo_light);
		}
	}

	public static void startActivity(Context context, CategoryItem catItem, ArrayList<ChapterItem> chapterItems, int position, int scrollPos, boolean firstTime) {
		Intent intent = new Intent(context, ReaderActivity.class);
		intent.putExtra("CATEGORY", catItem);
		intent.putExtra("POSITION", position);
		intent.putExtra("SCROLLPOSY", scrollPos);
		intent.putExtra("FIRSTTIME", firstTime);
//		intent.putParcelableArrayListExtra("DATA", chapterItems);
		context.startActivity(intent);
	}
	
	public static void startActivity(Context context, CategoryItem catItem, ArrayList<ChapterItem> chapterItems, int position, int scrollPos, boolean firstTime, OnStartActivityCallBack callback) {
		Intent intent = new Intent(context, ReaderActivity.class);
		intent.putExtra("CATEGORY", catItem);
		intent.putExtra("POSITION", position);
		intent.putExtra("SCROLLPOSY", scrollPos);
		intent.putExtra("FIRSTTIME", firstTime);
//		intent.putParcelableArrayListExtra("DATA", chapterItems);
		if (callback != null) {
			callback.onDone(intent);
		}
	}
	
	public class ReaderPagerAdapter extends FragmentStatePagerAdapter {

		public ReaderPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			try {
				ChapterItem chapterItem = mChapterItems.get(position);
				String filePath = Configuration.MULTI_FOLDER_DATA ? String.format("asset://gzip:%s/files/%s", mCategoryItem.getPath(), chapterItem.getPath()) : chapterItem.getPath();
				if (Configuration.LOAD_DATA_MODE == DataMode.ONLINE) {
					filePath = String.format("%s/%s/files/%s", Configuration.DATA_URL_BASE, mCategoryItem.getPath(), chapterItem.getPath());
				}
				return WebviewReaderFragment.newInstance(position, filePath, mCurrentPos == position ? mScrollPosY : 0);
			} catch(NullPointerException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		public int getCount() {
			return mChapterItems.size();
		}
		
		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}
	}
	
	public enum TypeDisplayButton {
		ONLY_PREV_BTN, ONLY_NEXT_BTN, BOTH
	}
	
	public class ReaderButtonHandler implements OnClickListener {
		
		private ImageView prevBtn, nextBtn;
		
		public ReaderButtonHandler(ImageView prevBtn, ImageView nexBtn) {
			this.prevBtn = prevBtn;
			this.nextBtn = nexBtn;
			this.nextBtn.setOnClickListener(this);
			this.prevBtn.setOnClickListener(this);
		}
		
		public ReaderButtonHandler(ViewGroup root, int prevBtnId, int nextBtnId) {
			if (root != null) {
				prevBtn = (ImageView) root.findViewById(prevBtnId);
				nextBtn = (ImageView) root.findViewById(nextBtnId);
			}
		}
		
		public void showButton(int position) {
			if (position >= (mChapterItems.size() - 1)) {
				mButtonHandler.showButton(TypeDisplayButton.ONLY_PREV_BTN);
			} else if(position > 0) {
				mButtonHandler.showButton(TypeDisplayButton.BOTH);
			} else {
				mButtonHandler.showButton(TypeDisplayButton.ONLY_NEXT_BTN);
			}
		}
		
		private Runnable hideButtonRun = new Runnable() {
			
			@Override
			public void run() {
				prevBtn.setVisibility(View.GONE);
				nextBtn.setVisibility(View.GONE);
			}
		};
		
		public void showButton(TypeDisplayButton type) {
			showOrHideButton(type, true);
		}
		
		public void showOrHideButton(TypeDisplayButton type, boolean isShow) {
			switch(type) {
				case BOTH:
					prevBtn.setVisibility(isShow ? View.VISIBLE : View.GONE);
					nextBtn.setVisibility(isShow ? View.VISIBLE : View.GONE);
					break;
				case ONLY_NEXT_BTN:
					nextBtn.setVisibility(isShow ? View.VISIBLE : View.GONE);
					prevBtn.setVisibility(isShow ? View.GONE : View.VISIBLE);
					break;
				case ONLY_PREV_BTN:
					prevBtn.setVisibility(isShow ? View.VISIBLE : View.GONE); 
					nextBtn.setVisibility(isShow ? View.GONE : View.VISIBLE);
					break;
				}
			
			if (isShow) {
				mHandler.removeCallbacks(hideButtonRun);
				mHandler.postDelayed(hideButtonRun, 2500);
			}
		}

		@Override
		public void onClick(View v) {
			int pos = mViewPager.getCurrentItem();
			if (v.equals(nextBtn)) {
				if (pos < mChapterItems.size() - 1) {
					mViewPager.setCurrentItem(pos+1, true);
				}
			} else if (v.equals(prevBtn)) {
				if (pos > 0) {
					mViewPager.setCurrentItem(pos-1, true);
				}
			}
		}
	}

	@Override
	public void onPageScrollStateChanged(int position) {
	}

	@Override
	public void onPageScrolled(int position, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int position) {
		try {
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			setSubtitle(position);
			mButtonHandler.showButton(position);
			if (mBannerHelper != null) mBannerHelper.loadAd();
		} catch(NullPointerException e) {
		}
	}
	
	public void setSubtitle(int position) {
		try {
			ChapterItem chapterItem = mChapterItems.get(position);
			mCurrentPos = position;
			String subtitle = mCategoryItem.getName().equals("") ? chapterItem.getName() : String.format("%s > %s", mCategoryItem.getName(), chapterItem.getName());
			if (!"".equals(subtitle.trim()))
				getSupportActionBar().setSubtitle(subtitle);
			else
				getSupportActionBar().setSubtitle(getString(R.string.author));
		} catch(IndexOutOfBoundsException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onSingleTapConfirmed(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onDoubleTap(MotionEvent e) {
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			mPopupWindow.showAtLocation(mMainLayout, Gravity.BOTTOM, 0, 0);
		}
		return false;
	}

	@Override
	public boolean onDoubleTapEvent(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onDown(MotionEvent e) {
		mButtonHandler.showButton(mViewPager.getCurrentItem());
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		return false;
	}

	public void onBack() {
		Intent intent = new Intent();
		intent.putExtra("position", mCurrentPos);
		intent.putExtra("visited", true);
		setResult(RESULT_OK, intent);
		super.onBackPressed();
	}
	
	@Override
	public void onBackPressed() {
		savedBookmark();
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			DialogHelper.showConfirm(this, "Đánh dấu chương đang đọc ?", new IDialogHelper() {
				
				@Override
				public void onOk() {
					onBack();
				}
				
				@Override
				public void onCancel() {
					onBack();
				}
			}, false);
		}
	}
	
	@Override
	public void onScroll(int position, int scrollPosX, int scrollPosY) {
		mScrollPosY = scrollPosY;
	}

	@Override
	public void onChangeBackground(int color) {
	}
	
}
